package com.oswift.gpm.web.action;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.gpm.entity.ErrorBean;
import com.oswift.gpm.entity.MessageBean;
import com.oswift.gpm.entity.PageBean;
import com.oswift.gpm.entity.SystemModuleBean;
import com.oswift.gpm.entity.UserBean;
import com.oswift.gpm.service.IUserService;
import com.oswift.gpm.utils.Constant;
import com.oswift.gpm.utils.PageCode;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.CipherUtil;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.PlatException;

@Controller
public class UserAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(UserAction.class);

    /**
     * UserServiceImpl spring注入实例
     */
    @Resource
    private IUserService userService;

    /**
     *
     * 加载新增页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/loadAddUser", method = RequestMethod.GET)
    public ModelAndView loadAddUser()
    {
        ModelAndView mv = new ModelAndView(Constant.PageName.USER);
        mv.addObject(METHOD, METHOD_ADD);
        return mv;
    }

    /**
     *
     * 加载修改页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/loadUpdateUser", method = RequestMethod.GET)
    public ModelAndView loadUpdateUser(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String uId = request.getParameter("id");
            if (StringUtil.isEmpty(uId))
            {
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
                mv.addObject("bean", bean);
            }
            else
            {
                UserBean bean = userService.getUserDetail(Integer.valueOf(uId));
                mv = new ModelAndView(Constant.PageName.USER);
                mv.addObject("bean", bean);
                mv.addObject(METHOD, METHOD_UPDATE);
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to loadUpdateUser error.", e);
            mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }

        return mv;
    }

    /**
     *
     * 新增一条用户信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/addUser", method = RequestMethod.POST)
    @ResponseBody
    public Object addUser(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            UserBean bean = getParameters(request);
            String sysId = request.getParameter("sysId");

            if (!StringUtil.isEmpty(bean.getUserName())
                    || !StringUtil.isEmpty(bean.getPassword())
                    || !StringUtil.isEmpty(bean.getTrueName()))
            {
                // 对密码进行加密
                bean.setPassword(CipherUtil
                        .generatePassword(bean.getPassword()));

                boolean isSuccess = userService.addUser(bean, sysId);
                if (isSuccess)
                {
                    messBean.setCode(PageCode.COMMON_SUCCESS);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.USER_ADD_SUCCESS));
                }
                else
                {
                    messBean.setCode(PageCode.USER_ADD_FAIL);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.USER_ADD_FAIL));
                }
            }
            else
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to save User info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        catch (Exception e)
        {
            log.error("Fail to save User info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 获取user列表，带分页
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     */
    @RequestMapping(value = "/security/getUserList", method = RequestMethod.GET)
    public ModelAndView getUserList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        String s_PageNum = request.getParameter("pageNum");

        int pageNum = DEFAULT_PAGENUM;
        if (!StringUtil.isEmpty(s_PageNum))
        {
            pageNum = Integer.valueOf(s_PageNum);
        }
        try
        {
            PageBean bean = userService
                    .getUserList(this.pageRecordNum, pageNum);
            mv = new ModelAndView(Constant.PageName.USERLIST);
            mv.addObject("pageBean", bean);
        }
        catch (PlatException e)
        {
            log.error("Get getUserList info is error.", e);
            mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 获取有分页的用户列表
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/getCheckUserList", method = RequestMethod.GET)
    public ModelAndView getCheckUserList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        String s_PageNum = request.getParameter("pageNum");

        int pageNum = DEFAULT_PAGENUM;
        if (!StringUtil.isEmpty(s_PageNum))
        {
            pageNum = Integer.valueOf(s_PageNum);
        }
        try
        {
            PageBean bean = userService
                    .getUserList(this.pageRecordNum, pageNum);
            mv = new ModelAndView(Constant.PageName.CHECKUSERLIST);
            mv.addObject("pageBean", bean);
        }
        catch (PlatException e)
        {
            log.error("Get getUserList info is error.", e);
            mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 根据Id获取用户信息详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/getUserDetail", method = RequestMethod.GET)
    public ModelAndView getUserDetail(HttpServletRequest request)
    {
        ModelAndView mv = null;
        String s_Id = request.getParameter("id");

        try
        {
            if (StringUtil.isEmpty(s_Id))
            {
                mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setMessInfo(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
            }
            else
            {
                UserBean bean = userService
                        .getUserDetail(Integer.valueOf(s_Id));
                mv = new ModelAndView(Constant.PageName.USERDETAIL);
                mv.addObject("bean", bean);
            }
        }
        catch (PlatException e)
        {
            log.error("Get getUserDetail info is error.", e);
            mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 获取页面post过来的数据参数
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @return UserBean
     */
    private UserBean getParameters(HttpServletRequest request)
    {
        UserBean bean = new UserBean();
        String userName = request.getParameter("userName").trim();
        String password = request.getParameter("password") != null ? request
                .getParameter("password").trim() : null;
        String enableMultiLogin = request.getParameter("enableMultiLogin")
                .trim();
        String loginErrorTime = request.getParameter("loginErrorTime").trim();
        String lockTime = request.getParameter("lockTime").trim();
        String status = request.getParameter("status").trim();
        String enableModifyPassword = request.getParameter(
                "enableModifyPassword").trim();
        String accountExpires = request.getParameter("accountExpires").trim();
        String trueName = request.getParameter("trueName").trim();
        String sex = request.getParameter("sex").trim();
        String position = request.getParameter("position").trim();
        String email = request.getParameter("email").trim();
        String qq = request.getParameter("qq").trim();
        String officePhone = request.getParameter("officePhone").trim();
        String homePhone = request.getParameter("homePhone").trim();
        String mobile = request.getParameter("mobile").trim();
        String address = request.getParameter("address").trim();
        String zipCode = request.getParameter("zipCode").trim();
        String birthday = request.getParameter("birthday").trim();
        String idCard = request.getParameter("idCard").trim();

        bean.setUserName(userName);
        bean.setPassword(password);
        if (StringUtil.isEmpty(enableMultiLogin))
        {
            bean.setEnableMultiLogin(true);
        }
        else
        {
            bean.setEnableMultiLogin(Boolean.valueOf(enableMultiLogin));
        }
        if (StringUtil.isEmpty(loginErrorTime))
        {
            bean.setLoginErrorTime(0);
        }
        else
        {
            bean.setLoginErrorTime(Integer.valueOf(loginErrorTime));
        }
        if (StringUtil.isEmpty(lockTime))
        {
            bean.setLockTime(0);
        }
        else
        {
            bean.setLockTime(Integer.valueOf(lockTime));
        }
        if (StringUtil.isEmpty(status))
        {
            bean.setStatus(0);
        }
        else
        {
            bean.setStatus(Integer.valueOf(status));
        }
        if (StringUtil.isEmpty(enableModifyPassword))
        {
            bean.setEnableModifyPassword(true);
        }
        else
        {
            bean.setEnableModifyPassword(Boolean.valueOf(enableModifyPassword));
        }
        if (StringUtil.isEmpty(accountExpires))
        {
            bean.setAccountExpires(null);
        }
        else
        {
            bean.setAccountExpires(TimeUtil.stringToDate(accountExpires,
                    TimeUtil.ISO_DATE_FORMAT));
        }
        bean.setTrueName(trueName);
        bean.setSex(sex);
        bean.setPosition(position);
        bean.setEmail(email);
        bean.setQq(qq);
        bean.setOfficePhone(officePhone);
        bean.setHomePhone(homePhone);
        bean.setMobile(mobile);
        bean.setAddress(address);
        bean.setZipCode(zipCode);
        if (StringUtil.isEmpty(birthday))
        {
            bean.setBirthday(null);
        }
        else
        {
            bean.setBirthday(birthday);
        }
        bean.setIdCard(idCard);

        return bean;
    }

    /**
     *
     * 根据userId查询和此用户关联的系统
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/getSysByUId", method = RequestMethod.GET)
    @ResponseBody
    public Object getSysByUId(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String uId = request.getParameter("id");
            if (StringUtil.isEmpty(uId))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
            }
            else
            {
                List<SystemModuleBean> beans = userService.getSysByUserId(uId);
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setObjContent(beans);
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to getSysByUId error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 修改用户信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/updateUser", method = RequestMethod.POST)
    @ResponseBody
    public Object updateUser(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            UserBean bean = getParameters(request);
            String sysId = request.getParameter("sysId");
            String userId = request.getParameter("id");

            if (!StringUtil.isEmpty(bean.getUserName())
                    || !StringUtil.isEmpty(userId)
                    || !StringUtil.isEmpty(bean.getTrueName()))
            {
                bean.setUserId(Integer.valueOf(userId));

                boolean isSuccess = userService.updateUser(bean, sysId);
                if (isSuccess)
                {
                    messBean.setCode(PageCode.COMMON_SUCCESS);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.USER_UPDATE_SUCCESS));
                }
                else
                {
                    messBean.setCode(PageCode.USER_UPDATE_FAIL);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.USER_UPDATE_FAIL));
                }
            }
            else
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
            }
        }
        catch (Exception e)
        {
            log.error("Fail to update User info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 根据UserId删除用户
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/delUser", method = RequestMethod.GET)
    @ResponseBody
    public Object delUser(HttpServletRequest request)
    {
        String userId = request.getParameter("id");

        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(userId))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));

                return messBean;
            }

            // 删除
            boolean isSuccess = userService.delUser(userId);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.USER_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.USER_DEL_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.USER_DEL_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to delUser error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 修改用户状态
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/updateUStatus", method = RequestMethod.POST)
    @ResponseBody
    public Object updateUserStatus(HttpServletRequest request)
    {
        String userId = request.getParameter("userId");
        String status = request.getParameter("status");

        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(status))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));

                return messBean;
            }

            // 修改状态
            boolean isSuccess = userService.updateUserStatus(Integer
                    .valueOf(userId), Integer.valueOf(status));

            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.UPDATE_USER_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.UPDATE_USER_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.UPDATE_USER_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to updateUserStatus error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 加载用户权限设置页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/loadSettingRight", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView loadSettingRight(HttpServletRequest request)
    {
        ModelAndView mv = null;
        String userId = request.getParameter("id");

        try
        {
            if (StringUtil.isEmpty(userId))
            {
                mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setMessInfo(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
            }
            else
            {
                List<SystemModuleBean> sysList = userService
                        .getSysByUserId(userId);
                mv = new ModelAndView(Constant.PageName.SETTINGRIGHT);
                mv.addObject("sysBean", sysList);
            }
        }
        catch (PlatException e)
        {
            log.error("Get loadSettingRight info is error.", e);
            mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 获取角色和组数据
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/getRightData")
    @ResponseBody
    public Object getRightData(HttpServletRequest request)
    {
        String userId = request.getParameter("uid");
        String systemId = request.getParameter("sid");

        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(systemId))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));

                return messBean;
            }

            Map<String, Object> map = userService.getSettingsRightData(Integer
                    .valueOf(userId), Integer.valueOf(systemId));
            if (null == map)
            {
                messBean.setCode(PageCode.GET_RIGHTDATA_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_RIGHTDATA_FAIL));
            }
            else
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setObjContent(map);
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to getRightData error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 设置权限
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/settingRight", method = RequestMethod.POST)
    @ResponseBody
    public Object settingRight(HttpServletRequest request)
    {
        String userId = request.getParameter("uid");
        String systemId = request.getParameter("sid");
        String roleIds = request.getParameter("rid");
        String groupIds = request.getParameter("gid");

        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(systemId))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));

                return messBean;
            }

            if (StringUtil.isEmpty(roleIds) && StringUtil.isEmpty(groupIds))
            {
                messBean.setCode(PageCode.NO_SETTINGRIGHT);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.NO_SETTINGRIGHT));

                return messBean;
            }

            boolean isSuccess = userService.settingRight(Integer
                    .valueOf(userId), Integer.valueOf(systemId), roleIds,
                    groupIds);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.SETTINGRIGHT_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.SETTINGRIGHT_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.SETTINGRIGHT_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to settingRight error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }

        return messBean;
    }

    public void setUserService(IUserService userService)
    {
        this.userService = userService;
    }
}
